﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "PadButton.h"

#include <QAudioRecorder>
#include <QUrl>
#include <QFileDialog>
#include <QTimer>


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QWidget* w = new QWidget(this);
    _layout = new QGridLayout(w);
    int cnt=0;int col=0;
    while(cnt<9){
        PadButton* pad = new PadButton(this);
        _pads.append(pad);

        if(cnt<3) {
            _layout->addWidget(pad,0,col);
            col++;
        }
        else _layout->addWidget(pad);
        cnt++;
    }

    ui->widget_pad->setLayout(_layout);
    ui->lineEdit_bpm->setText("120");
    ui->lineEdit_bat->setText("4");

    _recorder = new QAudioRecorder(this);

    _timer = new QTimer(this);
    connect(_timer,&QTimer::timeout,this,&MainWindow::start);
    calInterval();
    _timer->start();

    // 录音计时
    _recordTimer = new QTimer(this);
    connect(_recordTimer,&QTimer::timeout,this,[this](){
        ui->label_record->setText(QString("record time: %1s").arg(++_cnt));
    });
}

MainWindow::~MainWindow()
{
    if(_layout) delete _layout;
    if(_recorder) delete _recorder;
    delete ui;
}

void MainWindow::start()
{
    qDebug()<<"loop";
    for(auto pad:_pads){
            pad->play();
    }
}

void MainWindow::calInterval()
{
    int bpm = ui->lineEdit_bpm->text().toInt();
    int bat = ui->lineEdit_bat->text().toInt();
    int interval = (60.0/bpm) *bat *2; //每拍几秒*几拍*2小节
    qDebug()<<interval;
    _timer->setInterval(interval*1000);
}


void MainWindow::on_actionRecord_triggered()
{
    if(_recorder->state()==QMediaRecorder::StoppedState)
        {
            //开始音频设置
            _recorder->setOutputLocation(QFileDialog::getSaveFileUrl(this,"file",QUrl("D:\\"),"*.wav"));
            _recorder->setAudioInput(_recorder->defaultAudioInput());

            QAudioEncoderSettings settings;
            settings.setCodec("audio/pcm");
            settings.setSampleRate(44100);
            //settings.setBitRate(ui->cbbitrate->currentText().toInt());
            settings.setChannelCount(1);
            settings.setQuality(QMultimedia::HighQuality);
            settings.setEncodingMode(QMultimedia::ConstantQualityEncoding );

            _recorder->setAudioSettings(settings);
        }

        _recorder->record();
        _recordTimer->start(1000);
}


void MainWindow::on_actionStop_triggered()
{
    _recorder->stop();
    _recordTimer->stop();
    _cnt=0;
}


void MainWindow::on_actionStart_triggered()
{
    start();
}


void MainWindow::on_pushButton_clicked()
{
    calInterval();
}

